package com.lichuang.fruitvarietysm.user.controller;

import com.lichuang.fruitvarietysm.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("//user/baseinfo")
public class BaseInfoController {


    @Autowired
    private UserController userController;

    @PostMapping("/baseInfoSet")
    public User baseInfoSet(User user, @CookieValue(value = "loginToken") String loginToken) {
        user = userController.updateUserWithRedis(user, loginToken);
        return user;
    }

    @PostMapping("/uploadUserPhoto")
    public String uploadUserPhoto(MultipartFile file, @CookieValue(value = "loginToken") String loginToken, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            return "上传失败";
        }
        User user = userController.getCurrentUser(loginToken);
        if (user == null) {
            return "请先登录";
        }
        // 获取resources下的static文件，下面用来获取绝对路径
        File path = new File(ResourceUtils.getURL("classpath:static").getPath());
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//        // 此文件用来将传过来的MultipartFile转换为File
//        File tempFile = new File(file.getOriginalFilename());
//        // 将传过来的MultipartFile转换为File,此方法会在项目根目录生成文件
//        FileUtil.inputStreamToFile(file.getInputStream(), tempFile);
//        // 将当前时间戳和文件SHA1值前20位当作文件名防止重复
//        String fileName = System.currentTimeMillis() + MD5Util.getFileMD5(tempFile, "SHA1").substring(0, 20) + suffix;
//        // 删除之前生成的文件
//        tempFile.delete();
        // 使用UUID生成文件名
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        File dest = new File(path.getAbsolutePath(), "photo/user/profilephoto/" + fileName);
        file.transferTo(dest);
        user.setProfilePhoto("http://localhost:8080/photo/user/profilephoto/" + fileName);
        userController.updateUserWithRedis(user,loginToken);
        response.sendRedirect("http://127.0.0.1:8020/guoduoyang/baseInfo.html");
        return "上传成功";
    }

}
